from rest_framework import serializers
from api.models import Order, OrderDetail

class OrderDetailSerializer(serializers.ModelSerializer):
    detail_id = serializers.IntegerField(required=False)
    class Meta:
        model = OrderDetail
        fields = ['detail_id', 'product_id', 'product_name', 'quantity']

class OrderDetailSerializerALL(serializers.ModelSerializer):
    detail_id = serializers.IntegerField(required=False)
    class Meta:
        model = OrderDetail
        fields = ['order_id','detail_id', 'product_id', 'product_name', 'quantity']

class OrderSerializer(serializers.ModelSerializer):
    detail = OrderDetailSerializerALL(required=True, many=True)

    class Meta:
        model = Order
        fields = ['order_id', 'customer', 'order_date', 'status', 'remarks', 'detail']
        extra_kwargs = { # 前面传来的json中的字段是否缺失，必须字段检测
            # 'task': {
            #     'required': False,
            # }
        }

    def create(self, validated_data):
        formula_data = validated_data.pop('detail')
        order = Order.objects.create(**validated_data)
        OrderDetail.objects.create(order_id=order, **formula_data)
        return order

class OrderSerializerList(serializers.ModelSerializer):
    detail = OrderDetailSerializer(required=True, many=True)

    class Meta:
        model = Order
        fields = ['order_id', 'customer', 'order_date', 'status', 'remarks', 'detail']
        extra_kwargs = { # 前面传来的json中的字段是否缺失，必须字段检测
            # 'task': {
            #     'required': False,
            # }
        }

    def create(self, validated_data):
        detail_data = validated_data.pop('detail')
        order = Order.objects.create(**validated_data)
        for detail in detail_data:
            OrderDetail.objects.create(order_id = order, **detail)
        return order
    
    def update(self, instance, validated_data):
        detail_datas = validated_data.pop('detail')

        # 更新主模型字段
        for attr, value in validated_data.items():
            setattr(instance, attr, value)
        instance.save()

        # 获取现有关联对象
        existing_formulas = {f.detail_id: f for f in instance.detail.all()}

        for detail_data in detail_datas:
            detail_id = detail_data.get('detail_id')
            if detail_id and detail_id in existing_formulas:
                detail = existing_formulas[detail_id]
                for key ,value in detail_data.items():
                    setattr(detail,key,value)
                detail.save()
                existing_formulas.pop(detail_id)
            else:
                OrderDetail.objects.create(order_id = instance , **detail_data)
        
        for detail in existing_formulas.values():
            detail.delete()

        return instance